package com.cn.jdia.tas.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/control")
public class DownloadController {

	@RequestMapping("/download2")
	public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {

		String contextPath = request.getServletContext().getRealPath("/");
		String filename = contextPath + "\\files\\tao+.apk";

		File file = new File(contextPath + "\\files\\tao+.apk");

		byte[] body = null;
		InputStream is = new FileInputStream(file);
		body = new byte[is.available()];
		is.read(body);

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.add("Content-Disposition", "attchement;filename=" + file.getName());

		HttpStatus statusCode = HttpStatus.OK;

		ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);

		return entity;
	}

	@RequestMapping("/download")
	public static void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String contextPath = request.getServletContext().getRealPath("/");
		String filename = contextPath + "\\files\\tao+.apk";
		filename = new String(filename.getBytes("iso8859-1"), "UTF-8");

		File file = new File(filename);

		if (file == null || !file.exists()) {
			return;
		}

		OutputStream out = null;
		try {
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
			out = response.getOutputStream();

			byte[] body = null;
			InputStream is = new FileInputStream(file);
			body = new byte[is.available()];
			is.read(body);

			out.write(body);
			out.flush();
			out.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
